﻿using System;
using System.IO;
using System.Collections.Generic;
using System.IO.Compression;
using System.Net;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using CommDll;
using System.Management;
using System.Xml.Linq;
using System.Xml;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;


namespace HospitalMedicineTraceability
{
    /// <summary>
    /// 系统处理类
    /// </summary>
    public class AppInfo
    {
        #region 000 窗体动画函数
        /// <summary>
        /// 窗体动画函数
        /// </summary>
        /// <param name="hwnd">指定产生动画的窗口的句柄</param>
        /// <param name="dwTime">指定动画持续的时间</param>
        /// <param name="dwFlags">指定动画类型，可以是一个或多个标志的组合。</param>
        /// <returns></returns>
        [DllImport("user32")]
        public static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);

        //下面是可用的常量，根据不同的动画效果声明自己需要的
        public const int AW_HOR_POSITIVE = 0x0001;//自左向右显示窗口，该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志
        public const int AW_HOR_NEGATIVE = 0x0002;//自右向左显示窗口，该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志
        public const int AW_VER_POSITIVE = 0x0004;//自顶向下显示窗口，该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志
        public const int AW_VER_NEGATIVE = 0x0008;//自下向上显示窗口，该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志该标志
        public const int AW_CENTER = 0x0010;//若使用了AW_HIDE标志，则使窗口向内重叠；否则向外扩展
        public const int AW_HIDE = 0x10000;//隐藏窗口
        public const int AW_ACTIVE = 0x20000;//激活窗口，在使用了AW_HIDE标志后不要使用这个标志
        public const int AW_SLIDE = 0x40000;//使用滑动类型动画效果，默认为滚动动画类型，当使用AW_CENTER标志时，这个标志就被忽略
        public const int AW_BLEND = 0x80000;//使用淡入淡出效果
        #endregion

        #region 001 调用系统api
        // 显示系统窗体
        [DllImport("User32.dll")]
        public static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        public const int WS_SHOWNORMAL = 1;
        // 设置窗体到最前端
        [DllImport("User32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
        // 取窗体线程
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
        #endregion

        #region 002 自定义属性
        // 升级程序
        public static string m_strUpdaterFileName = string.Format("{0}\\{1}", System.Windows.Forms.Application.StartupPath, "AutoUpdater.exe");
        // 本系统App相关
        public static string m_strAppName = ""; // 程序名称
        public static string m_strCompany = ""; // 公司名称
        public static string m_strCopyright = ""; // 公司名称
        public static string m_strAppVer = "2.0619.01";  // 程序版本号
        public static Icon m_iconApp = null;    // 程序图标
        public static Boolean m_bDbConnected = false;  //数据库是否连接
        public static Boolean m_bIsWebserverDB = false;  // 是否WebService数据库

        public static bool m_bLogin;    // 是否通过系统登录验证
        public static UserInfo m_UserInfo = new UserInfo();    // 用户信息 
        public static DataTable m_dtWarehouse;    // 仓库数据        
        public static DataTable m_dtFunction;   // 系统功能(设置功能时用)
        public static Color m_colorDgvCurrent = Color.LightSteelBlue; // dgv当前行底色

        public static frmMain m_frmMain = null; // 主窗体

        #endregion

        static AppInfo(){
            // 取程序集相关信息
            Assembly asm = Assembly.GetExecutingAssembly();
            m_strAppName = ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyTitleAttribute))).Title.ToString();
            m_strCopyright = ((AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyCopyrightAttribute))).Copyright.ToString();
            m_strCompany = ((AssemblyCompanyAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyCompanyAttribute))).Company.ToString();
            //m_strAppVer = asm.GetName().Version.ToString();
            // 取图标信息
            m_iconApp = Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
        }

        #region 003 系统类
        /// <summary>
        /// 是否有相同实例在运行,第一次运行，返回null
        /// </summary>
        /// <param name="bIsShow">是否显示进程</param>
        /// <returns></returns>
        public static Process _runningInstance(Boolean bIsShow = true)
        {
            Process processCurrent = Process.GetCurrentProcess();
            Process[] processList = Process.GetProcessesByName(processCurrent.ProcessName);
            foreach (Process process in processList)
            {
                if (process.Id != processCurrent.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\").ToLower() == processCurrent.MainModule.FileName.ToLower())
                    {
                        // 是否要显示进程
                        if (bIsShow)
                        {
                            _handleRunningInstance(process);
                        }
                        return process;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 显示正在运行的进程当前窗口
        /// </summary>
        /// <param name="instance"></param>
        public static void _handleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, 1); //置窗口为正常状态
            SetForegroundWindow(instance.MainWindowHandle);
        }
              
        /// <summary>
        /// 是否进行系统更新
        /// </summary>
        public static Boolean _isUpdate()
        {
            Boolean bResult = false;
            // 01 取需更新文件数以及相关配置文件是否合法
            bResult = (AppUpdater._checkForUpdate() > 0);
            if (bResult)
            {
                if (CommFun._messageBoxShow("系统检测到新版本，是否需要更新？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                {
                    bResult = true;
                }
                else
                {
                    bResult = false;
                }
            }
            // 02 更新
            if (bResult)
            {
                // 启动更新程序
                Process.Start(AppInfo.m_strUpdaterFileName);
                Environment.Exit(0);
                Application.ExitThread();
                Application.Exit();
            }
            return bResult;
        }
        #endregion

        #region 004 数据库访问方法
        /// <summary>
        /// 连接数据库
        /// 如果数据库连接不正常，弹出数据库设置窗体
        /// </summary>
        public static Boolean _connectDB()
        {
            Boolean bResult = false;
            DbHelper._initDb(); // 数据库初始化
            if (!DbHelper.DBAccess[0].m_bConnected)
            {
                DbHelper._connectDb();
            }
            bResult = DbHelper.DBAccess[0].m_bConnected;
            return bResult;
        }

        /// <summary>
        /// 连接数据库
        /// 如果数据库连接不正常，弹出数据库设置窗体
        /// </summary>
        public static Boolean _connectDB_WS()
        {
            Boolean bResult = false;
            try
            {
                string strConnectionString = FunctionComm._getAppConfigKeyValue("ConnectionString");
                strConnectionString = (strConnectionString == null) ? ";" : FunctionComm._decryptDES(strConnectionString, "taihao12");
                AccessDB_WS.AccessDB.m_strWebserviceUrl = strConnectionString.Split(';')[0];
                AccessDB_WS.AccessDB.m_strDbName = strConnectionString.Split(';').Length > 1 ? strConnectionString.Split(';')[1] : "";
            }
            catch
            {
                AccessDB_WS.AccessDB.m_strDbName = "";
                AccessDB_WS.AccessDB.m_strWebserviceUrl = "";
            }
            if (!AccessDB_WS.AccessDB._connectDB())
            {
                frmDbConfig_WS frm = new frmDbConfig_WS();
                frm.ShowDialog();
            }
            bResult = AccessDB_WS.AccessDB.m_bIsConnected;
            return bResult;
        }

        /// <summary>
        /// 数据库取数据
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static DataSet _openSql_DataSet(string strSql)
        {
            DataSet ds = new DataSet();
            DataTable dt = _openSql_DataTable(strSql);
            if (dt != null)
            {
                ds.Tables.Add(dt);
            }
            return ds;
        }

        /// <summary>
        /// 数据库取单个数据
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static string _openSql_Value(string strSql)
        {
            string strReturn = "";
            DataTable dt = _openSql_DataTable(strSql);
            if (dt != null && dt.Rows.Count > 0)
            {
                strReturn = dt.Rows[0][0].ToString();
            }
            return strReturn;
        }

        /// <summary>
        /// 数据库取数据
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static DataTable _openSql_DataTable(string strSql)
        {
            DataTable dt = null;
            if (AppInfo.m_bIsWebserverDB)
            {
                dt = AccessDB_WS.AccessDB._openSql_dt(strSql);
            }
            else
            {
                dt = DbHelper.DBAccess[0]._openSql_Dt(strSql);
            }
            return dt;
        }        

        /// <summary>
        /// 执行Sql
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static int _execSql(string strSql)
        {
            int nResult = 0;
            if (AppInfo.m_bIsWebserverDB)
            {
                nResult = AccessDB_WS.AccessDB._execSQL(strSql);
            }
            else
            {
                nResult = DbHelper.DBAccess[0]._execSql(strSql);
            }
            return nResult;
        }

        /// <summary>
        /// 检测版本
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        public static Boolean _CheckVersion()
        {
            Boolean bResult = false;
            string strSql = "exec P_CheckVersion";
            DataTable dt = AppInfo._openSql_DataTable(strSql);
            string strStatus = "-1";
            string strMessage = "版本有误,请及时与软件服务商联系!";
            try
            {
                if (dt != null && dt.Rows.Count > 0)
                {
                    strStatus = dt.Rows[0]["IsOK"].ToString();
                    strMessage = dt.Rows[0]["Message"].ToString();
                }
            }
            catch { }            

            switch (strStatus)
            {
                case "-1":
                case "0":
                    // 不能登录
                    MessageBox.Show(strMessage, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    bResult = false;
                    break;
                case "1":
                    // 能登录，但有提示
                    MessageBox.Show(strMessage, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    bResult = true;
                    break;
                case "2":
                    // 正常
                    bResult = true;
                    break;
                default:
                    break;
            }

            return bResult;
        }
        #endregion
    }
}